<template>
  <view class="app-layout">
    <!-- <app-header></app-header> -->
    <view class="app-main">
      <app-sider pageKey="market"></app-sider>
      <view class="app-content">
        <view class="navbar-con">
          <view class="navbar-bar">
            <view v-for="(tab, index) in tabList" :key="index" class="tab-item" :class="{ active: currentTab == index }"
              @click="handlecurrentTab(index)">
              {{ tab }}
            </view>
          </view>
        </view>
        <template v-if="currentTab == 0">
          <view class="coupon-type-wrapper">
            <view class="coupon-type-item" @click="handleDiscount(0)">
              <view class="coupon-content">
                <view class="coupon-top">
                  <text class="coupon-title">商品立减券</text>
                  <view class="create-btn">+新建</view>
                </view>
                <text class="coupon-desc">单商品设置无门槛优惠券，提升商品转化</text>
              </view>
            </view>
            <view class="coupon-type-item" @click="handleDiscount(1)">
              <view class="coupon-content">
                <view class="coupon-top">
                  <text class="coupon-title">商品满减券</text>
                  <view class="create-btn">+新建</view>
                </view>
                <text class="coupon-desc">多商品满M元享受N折/减X元优惠</text>
              </view>
            </view>
          </view>
          <view class="order-search">
            <view class="" style="display: flex;margin-bottom:12px;">
              <view v-for="(tab, index) in tabType" :key="index" class="type-item"
                :class="{ activeType: currentTabType == index }" @click="handlecurrentTabType(index)">
                {{ tab }}
              </view>
            </view>
            <view class="" style="display: flex;">
              <uni-datetime-picker v-model="range" type="daterange" @maskClick="maskClick" @change="handleTime" />
              <u-search placeholder="请输入优惠券ID/名称" v-model="pageInfo.keyword" clearable bgColor="#fff"
                borderColor="#e5e5e5" :showAction="false" @search="handleSearch" @clear="handleReset"></u-search>

              <view class="flex-row" style="flex: 1">
                <u-button type="primary" text="搜索" @click="handleSearch"></u-button>
                <u-button :plain="true" text="重置" @click="handleReset"></u-button>
              </view>
            </view>
          </view>
        </template>
        <view class="market-wrapper" v-if="currentTab == 0">
          <view class="market-list">
            <scroll-view scroll-y="true" ref="scrollView" style="height: 100%; width: 100%"
              @scrolltolower="onScrollToLower">
              <template v-if="list.length>0">
                <view class="item-card" v-for="(item, index) in list" :key="index">
                  <view class="item-card-top">
                    <view class="left-area">
                      <image class="item-icon" src="@/static/imgs/jialiao.png" mode=""></image>
                      <view class="text-group">
                        <text class="item-name">新品立减10元券</text>
                        <view class="info-container">
                          <view class="info-row" style="gap:0 30px">
                            <view class="info-item">
                              <text class="info-label">状态：</text>
                              <text class="info-value status-unreleased" v-if="item.status==0">未发布</text>
                              <text class="info-value status-active" v-if="item.status==1">进行中</text>
                              <text class="info-value status-notstarted" v-if="item.status==2">未开始</text>
                              <text class="info-value status-end" v-if="item.status==3">已结束</text>
                              <text class="info-value status-pause" v-if="item.status==4">暂停中</text>
                            </view>
                            <view class="info-item">
                              <text class="info-label">类型：</text>
                              <text class="info-value">立减券</text>
                            </view>
                            <view class="info-item">
                              <text class="info-label">发放量：</text>
                              <text class="info-value">1000</text>
                            </view>
                            <view class="info-item">
                              <text class="info-label">领取量：</text>
                              <text class="info-value">0</text>
                            </view>
                            <view class="info-item">
                              <text class="info-label">透出时间：</text>
                              <text class="info-value">2025-08-08 00:00:00 ~ 2025-08-31 23:59:59</text>
                            </view>
                          </view>
                          <view class="info-row">
                            <view class="info-item">
                              <text class="info-label">适用场景：</text>
                              <text class="info-value">外卖配送、门店自提</text>
                            </view>
                            <view class="info-item">
                              <text class="info-label">创建人：</text>
                              <text class="info-value">张三</text>
                            </view>
                            <view class="info-item">
                              <text class="info-label">创建时间：</text>
                              <text class="info-value">2025-08-08 08:08:08</text>
                            </view>
                          </view>
                        </view>
                      </view>
                    </view>
                  </view>

                  <!-- 右侧：操作按钮 -->
                  <view class="right-area">
                    <view class="right-btn">
                      <!-- 未发布 暂停中 -->
                      <view class="operate-btn edit" @click="handleEdit(item)" v-if="item.status==0||item.status==4">
                        <image src="@/static/imgs/release.png" mode=""></image>
                        发布
                      </view>
                      <!--  -->
                      <view class="operate-btn edit" @click="handleEdit(item)">
                        <image src="@/static/imgs/see.png" mode=""></image>
                        查看
                      </view>
                      <!-- 进行中 未开始 -->
                      <view class="operate-btn edit" @click="handleOperation(item,2)" v-if="item.status==1||item.status==2">
                        <image src="@/static/imgs/pause.png" mode=""></image>
                        暂停
                      </view>
                      <!-- 未发布 暂停中 -->
                      <view class="operate-btn edit" @click="handleEdit(item)" v-if="item.status==0||item.status==4">
                        <image src="@/static/imgs/edit.png" mode=""></image>
                        编辑
                      </view>
                      <!-- 未发布  已结束-->
                      <view class="operate-btn" @click="handleOperation(item,0)" v-if="item.status==0||item.status==3">
                        <image src="@/static/imgs/trash.png" mode=""></image> 删除
                      </view>
                      <!-- 进行中 未开始  暂停中-->
                      <view class="operate-btn" @click="handleOperation(item,1)"
                        v-if="item.status==1||item.status==2||item.status==4">
                        <image src="@/static/imgs/enable.png" mode=""></image> 结束
                      </view>
                    </view>
                  </view>
                </view>

              </template>
              <template v-else>
                <view class="empty-box" style="text-align: center;padding-top: 12vh;">
                  <image src="/src/static/imgs/emptyW.png" mode="widthFix" style="width: 240px;"></image>
                  <view class="text1" style="color: #999;">暂无数据</view>
                </view>
              </template>
            </scroll-view>
          </view>

        </view>

      </view>
    </view>

  </view>
  <u-popup :show="show" @close="popupCancel" :round="10" mode="center">
    <view class="popup-cons" :style="{'max-width':showStatus==2?'396px':'330px','width':showStatus==2?'396px':'330px'}">
      <view class="applyfor-tit">
        {{ showTitle }}
      </view>
      <view class="applyfor-info">
        {{ showInfo }}
      </view>
      <view class="applyfor-info">
        {{ showInfos }}
      </view>
      <!-- 0 删除 1结束 2暂停 -->
      <view class="button-group">
        <button class="cancel-btn" @click="popupCancel">取消</button>
        <button class="pay-btn" @click="popupSure" v-if="showStatus==0">删除</button>
        <button class="pay-btn" @click="popupSure" v-if="showStatus==1">结束</button>
        <button class="pay-btn" @click="popupSure" v-if="showStatus==2">暂停</button>
      </view>
    </view>
  </u-popup>
</template>
<script setup>
  import {
    ref,
    computed,
    nextTick,
    reactive,
  } from 'vue'
  import {
    onLoad,
    onShow
  } from '@dcloudio/uni-app'
  import {
    getTreeCategory,
    productPage,
    deleteProducts,
    updatePublish,
    productPageCount
  } from '@/requests/apis/products'
  let currentTab = ref(0)
  let currentTabType = ref(0)

  let tabList = ref(['优惠券', '营销活动', '套餐商品', '广告弹窗', '营销轮播', '活动微页面'])
  let tabType = ref(['全部', '未发布', '进行中', '已结束'])
  let range = ref([])
  let show = ref(false)
  let showTitle = ref()
  let showStatus = ref(0)
  let showInfo = ref()
  let showInfos = ref()
  let pageInfo = reactive({
    total: 0,
    page: 1,
    limit: 20,
    keyword: '',
    status: undefined,
    sceneCode: undefined,
    categoryIds: undefined
  });

  const list = ref([{
    status: 0
  }, {
    status: 1
  }, {
    status: 2
  }, {
    status: 3
  }, {
    status: 4
  }])
  let isMergeRequest = false;
  const bottomInset = ref(0);
  onLoad(() => {
    // getCategoryList()
  })
  onShow(async () => {
    // #ifdef APP-PLUS
    uni.hideTabBar()
    // #endif

  })
  const getMerge = () => {
    const prevPage = pageInfo.page;
    if (prevPage !== 1) {
      isMergeRequest = true;
      pageInfo.limit = prevPage * 20;
      pageInfo.page = 1;
      getproductPage('merge');
    } else {
      pageInfo.page = 1;
      pageInfo.limit = 20;
      getproductPage();
    }
  };

  const onScrollToLower = (e) => {
    if (pageInfo.page * pageInfo.limit < pageInfo.total && goodsList.value.length >= 20) {
      pageInfo.page++;
      getproductPage('add');
    }
  }


  const getproductPage = async (type) => {
    uni.showLoading({
      title: '加载中',
      mask: true
    })
    try {
      let res = await productPage({
        ...pageInfo,
      })
      pageInfo.total = res.Result.total
      if (type === 'merge') {
        goodsList.value = res.Result.records || [];
        pageInfo.page = Math.ceil(goodsList.value.length / 20);
        pageInfo.limit = 20;
        isMergeRequest = false;
      } else if (type === 'add') {
        goodsList.value = [...goodsList.value, ...(res.Result.records || [])];
      } else {
        goodsList.value = res.Result.records || [];
      }

      getPageCount()
    } catch (error) {
      console.log(error);
      uni.hideLoading();
    } finally {
      uni.hideLoading();
    }

  }

  const handleTime = (e) => {
    if (e.length > 0) {
      pageInfo.startDate = e[0] + ' ' + '00:00:00'
      pageInfo.endDate = e[1] + ' ' + '23:59:59'
    } else {
      pageInfo.startDate = undefined
      pageInfo.endDate = undefined
    }
  }
  const handleSearch = () => {
    pageInfo.limit = 20;
    pageInfo.page = 1;
    getproductPage()
  }
  const handleReset = () => {
    pageInfo.limit = 20;
    pageInfo.page = 1;
    pageInfo.keyword = ''
    getproductPage()
  }

  // 切换
  const handlecurrentTab = async (index) => {
    console.log(index, 'iniinininiiiiiiii')
    currentTab.value = index
    pageInfo.status = undefined;
  }
  const handlecurrentTabType = (index) => {

    pageInfo.limit = 20;
    pageInfo.page = 1;
    currentTabType.value = index
    getproductPage()

  }
  // 新增
  const handleDiscount=(type)=>{
    if(type==0){
      uni.navigateTo({
        url:'/pages/market/instantDiscount'
      })
    }else {
      uni.navigateTo({
        url:'/pages/market/fullDiscount'
      })
    }
  }
  const handleOperation=(item,status)=>{
    show.value = true;
    showStatus.value = status;
    if(status==0){
      showTitle.value = '确认删除'
      showInfo.value = '优惠券删除后不可恢复。'
      showInfos.value = '是否确认继续删除？'
    }else if(status==1){
      showTitle.value = '确认结束'
      showInfo.value = '是否确认结束该优惠券的发放？'
      showInfos.value = '消费者已经领取的优惠券仍然可以使用。'
    }else if(status==2){
      showTitle.value = '确认暂停'
      showInfo.value = '暂停后仍可发布，是否确认暂停当前优惠券的发放？'
      showInfos.value = '消费者已经领取的优惠券仍然可以使用。'
    }

  }
  // 弹窗取消
  const popupCancel = () => {
    show.value = false
  }
  // 弹窗确认
  const popupSure = () => {
    show.value = false
    // uni.showLoading({
    //   title: '加载中',
    //   mask: true
    // })
    // // 删除 结束 暂停
    // if (showType.value == 0) {

    // } else if (showType.value == 1) {

    // } else if (showType.value == 2) {

    // }
  }

</script>

<style lang="scss" scoped>
  .tabs-wrapper {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-around;
    height: 44px;
    background: #fff;
    margin: 10px;

    :deep(.u-tabs) {
      width: 100% !important;

      .u-tabs__wrapper__nav__item {
        flex: 1 !important;
      }

      .u-tabs__wrapper__nav__item__text {
        white-space: nowrap;
      }
    }
  }

  .coupon-type-wrapper {
    display: flex;
    padding: 10px;
    box-sizing: border-box;
    gap: 10px;

    .coupon-type-item {
      padding: 13px 20px;
      box-sizing: border-box;
      width: 270px;
      background-color: #fff;
      border-radius: 8px;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);

      .coupon-content {
        .coupon-top {
          display: flex;
          justify-content: space-between;
          margin-bottom: 9px;
          align-items: center;

          .coupon-title {
            font-weight: 500;
            font-size: 14px;
            color: #333333;
            line-height: 20px;
          }

          .create-btn {
            align-self: flex-start;
            background-color: rgba(255, 122, 0, 0.1);
            font-weight: 500;
            font-size: 12px;
            color: #FF7A00;
            border-radius: 16px;
            padding: 5px 14px;
            box-sizing: border-box;
          }
        }

        .coupon-desc {
          font-weight: 400;
          font-size: 12px;
          color: #333333;
          line-height: 17px;
        }
      }
    }


  }

  .order-search {
    // display: flex;
    background-color: #fff;
    margin: 0px 10px 0;
    padding: 12px 145px 12px 20px;
    box-sizing: border-box;

    :deep(.uni-date) {
      margin-right: 10px;
    }

    :deep(.icon-calendar) {
      margin-left: 10px !important;
    }

    :deep(.uni-date__x-input) {
      height: 32px !important;
      line-height: 32px !important;
    }

    :deep(.range-separator) {
      height: 32px !important;
      line-height: 32px !important;
    }

    :deep(.uni-date-x--border) {
      border-radius: 100px !important;
    }

    :deep(.uni-date-x) {
      border-radius: 100px !important;
    }

    .type-item {
      font-weight: 400;
      font-size: 14px;
      color: #666666;
      display: flex;
      align-items: center;
      background: #f6f6f6;
      padding: 7px 12px;
      box-sizing: border-box;
      border-radius: 10px;
      margin-right: 10px;
    }

    .activeType {
      background: rgba(15, 144, 253, 0.1);
      color: #0f90fd;
    }

    :deep(button) {
      width: 74px;
      height: 38px;
      margin-left: 11px;
      margin-right: 0;
      border-radius: 100px;
    }

  }

  .market-wrapper {
    display: flex;
    flex: 1;
    overflow: hidden;

    .market-list {
      flex: 1;
      overflow: hidden;

      .item-card {
        padding: 21px 10px 10px 22px;
        box-sizing: border-box;
        border-radius: 8px;
        margin: 10px;
        background: #FFFFFF;

        .item-card-top {
          display: flex;
        }

        .left-area {
          display: flex;
          width: 100%;

          .item-icon {
            width: 40px;
            height: 40px;
            margin-right: 19px;
          }

          .text-group {
            display: flex;
            flex-direction: column;
            flex: 1;

            .item-name {
              font-weight: 500;
              font-size: 16px;
              color: #333333;
              line-height: 22px;
              margin-bottom: 10px;
            }

            .info-container {
              display: flex;
              flex-direction: column;
              gap: 10px;

              .info-row {
                display: flex;
                flex-wrap: wrap;
                gap: 65px;
                align-items: center;

                .info-item {
                  display: flex;
                  align-items: center;
                  font-weight: 400;
                  font-size: 14px;
                  color: #666666;

                  .status-active {
                    color: #07c160;
                  }

                  .status-unreleased {
                    color: #A16222;
                  }

                  .status-notstarted {
                    color: #1784FC;
                  }

                  .status-pause {
                    color: #E72C1A;
                  }

                  .status-end {
                    color: #9A9A9A;
                  }
                }
              }
            }
          }
        }


        /* 右侧区域：操作按钮 */
        .right-area {
          display: flex;
          justify-content: flex-end;

          .right-btn {
            display: flex;
            gap: 10px;
          }

          .operate-btn {
            display: flex;
            align-items: center;
            padding: 6px 12px;
            border-radius: 4px;
            box-sizing: border-box;
            font-weight: 400;
            font-size: 14px;
            color: #0F90FD;
            background: rgba(15, 144, 253, 0.1);
            border-radius: 100px;
            margin-top: 12px;

            image {
              width: 16px;
              height: 16px;
              margin-right: 2px;
            }
          }
        }
      }
    }

  }
</style>
